//
//  SceneContentView.swift
//  SpriteKitDemo
//
//  Created by lizhijun on 2023/4/21.
//

import UIKit

class NodeContentView: UIView {
    var stopClosure:(()->Void)?
    override func removeFromSuperview() {
        super.removeFromSuperview()
        
    }
    private(set) lazy var imgView :UIImageView = {
        let imgView = UIImageView()
        imgView.isUserInteractionEnabled = true
        return imgView
    }()
    
    
    private var gifView :FLAnimatedImageView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(imgView)
        let tap = UITapGestureRecognizer(target: self, action: #selector(stopGif))
        addGestureRecognizer(tap)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setupGIF(){
        gifView = FLAnimatedImageView()
        gifView?.isUserInteractionEnabled = true
        gifView?.isHidden = true
        gifView?.animationRepeatCount = 0
        gifView?.contentMode = .scaleAspectFill
        addSubview(gifView!)
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        imgView.frame = bounds
        
        gifView?.frame = bounds
    }
    
    func playGIf(){
        imgView.isHidden = true
        gifView?.isHidden = false
        let path = Bundle.main.path(forResource: "bear", ofType: "gif")
        let data = NSData(contentsOfFile: path ?? "") as? Data
        guard let data = data else {return}
        gifView?.animatedImage = FLAnimatedImage(animatedGIFData: data)
        gifView?.startAnimating()
    }
    @objc private func stopGif(){
        gifView?.isHidden = true
        gifView?.stopAnimating()
        imgView.isHidden = false
        self.stopClosure?()
    }
}
